﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Streambolics.Notes.Gui
{
    public partial class PasswordEdit : UserControl
    {
        public PasswordEdit ()
        {
            InitializeComponent ();
            try
            {
                string pw = Streambolics.Notes.Password.Retrieve ();
                if (!String.IsNullOrEmpty (pw))
                {
                    password.Text = pw;
                }
            }
            catch (Exception ex)
            {
                errorProvider.SetError (password, ex.Message);
            }
            RedrawImages ();
        }

        private void ShowPicture (PictureBox aPicture, ref uint hash)
        {
            int n = (int)(hash % imageList.Images.Count);
            aPicture.Image = imageList.Images[n];
            hash ^= hash >> 2;
        }

        private void RedrawImages ()
        {
            uint n = (uint)password.Text.GetHashCode ();
            ShowPicture (picture1, ref n);
            ShowPicture (picture2, ref n);
            ShowPicture (picture3, ref n);
            ShowPicture (picture4, ref n);
        }

        public event EventHandler PasswordChanged;

        protected virtual void OnPasswordChanged (EventArgs e)
        {
            RedrawImages ();
            if (PasswordChanged != null)
            {
                PasswordChanged.Invoke (this, e);
            }
        }

        private void password_TextChanged (object sender, EventArgs e)
        {
            OnPasswordChanged (e);
        }

        public void NotifyValid ()
        {
            errorProvider.SetError (password, "");
            if (checkBox_Remember.Checked)
            {
                Streambolics.Notes.Password.Store (Password);
            }
        }

        public Connection Connect ()
        {
            try
            {
                Connection c = new Connection (password.Text);
                NotifyValid ();
                return c;
            }
            catch (Exception ex)
            {
                errorProvider.SetError (password, ex.Message);
                return null;
            }
        }

        [Browsable (false)]
        public string Password
        {
            get
            {
                return password.Text;
            }
        }
    }
}
